# -*- coding: utf-8 -*-
#
# Author:: hanjunfeng
# Date:: 2022/7/7

from submodules.common.lib.datetime_ import get_timestamp_human

from lib import ths_
from lib.character import (
    get_golden_cross_combo,
    get_ma_up_combo,
    get_golden_cross_socre,
    get_throught_up_boll_times,
)
from lib.common import tx_code_to_ts_code, ts_code_to_ths_code
from lib.indicator import get_ma_list, get_boll_list
from lib.tx_ import get_market_info_all, get_code_list_tx_pre_screen

from lib.send_email import send_email_remind
from lib.ts_ import get_stock_list

from lib.ts_ import get_candles_data


def main():
    email_info_list = []
    stock_list = get_stock_list()
    market_info_all = get_market_info_all(stock_list)
    code_list_tx_pre_screen = get_code_list_tx_pre_screen(market_info_all)

    condition_list = set()

    # 测试
    # for tx_code in code_list_tx_pre_screen[:300]:
    for tx_code in code_list_tx_pre_screen:
        ts_code = tx_code_to_ts_code(tx_code)
        candles_data = get_candles_data(ts_code)
        ma_list_type3 = get_ma_list(candles_data, ma_type=3, offset=0)
        ma_list_type15 = get_ma_list(candles_data, ma_type=15, offset=0)
        ma_list_type20 = get_ma_list(candles_data, ma_type=20, offset=0)
        ma_list_type30 = get_ma_list(candles_data, ma_type=30, offset=0)
        boll_list_type15 = get_boll_list(candles_data, mid=15, offset=0)
        golden_cross_combo = get_golden_cross_combo(ma_list_type3, ma_list_type15)

        current_price = candles_data[0][4]
        high_price = candles_data[0][2]
        low_price = candles_data[0][3]
        low_price_offset1 = candles_data[1][3]
        low_price_offset2 = candles_data[2][3]

        gains_percent = round(candles_data[0][7], 2)
        ma_up_combo = get_ma_up_combo(ma_list_type3)
        ma_up_combo_type15 = get_ma_up_combo(ma_list_type15)
        ma_up_combo_type30 = get_ma_up_combo(ma_list_type30)

        # current_price_threshold = 20
        # if current_price > current_price_threshold:
        #     continue
        # condition_list.add(f"股价小于{current_price_threshold}")

        # gains_percent_threshold_left = -5
        # gains_percent_threshold_right = 3
        # if gains_percent < gains_percent_threshold_left or gains_percent > gains_percent_threshold_right:
        #     continue
        # condition_list.add(f"今日涨幅：>={gains_percent_threshold_left}，<={gains_percent_threshold_right}")

        # # 今日最低价低于MA15
        # if low_price > ma_list_type15[0]:
        #     continue
        # condition_list.add(f"今日最低价低于MA15")

        # # 今日最低价低于MA30
        # if low_price > ma_list_type30[0]:
        #     continue
        # condition_list.add(f"今日最低价低于MA30")

        if low_price > ma_list_type20[0]:
            continue
        condition_list.add(f"今日最低价：<=MA20")

        # low_price_list = [low_price, low_price_offset1, low_price_offset2]
        # if min(low_price_list) > ma_list_type20[0]:
        #     continue
        # condition_list.add(f"近3日最低价：<=MA20")

        # low_price_list = [low_price, low_price_offset1]
        # if min(low_price_list) > ma_list_type20[0]:
        #     continue
        # condition_list.add(f"近2日最低价：<=MA20")

        # 金叉持续次数>1
        # if golden_cross_combo < 1:
        #     continue

        # 短均线连续上涨次数为1或2
        # if ma_up_combo not in [1, 2]:
        #     continue

        ma_up_combo_threshold = 1
        if ma_up_combo > ma_up_combo_threshold:
            continue
        condition_list.add(f"MA3线连续上涨次数：<={ma_up_combo_threshold}")

        # # 短均线连续上涨次数=1
        # if ma_up_combo != 1:
        #     continue

        ma_up_combo_type15_threshold = 1
        if ma_up_combo_type15 < 1:
            continue
        condition_list.add(f"MA15连续上涨次数：>={ma_up_combo_type15_threshold}")

        ma_up_combo_type30_threshold = 1
        if ma_up_combo_type30 < 1:
            continue
        condition_list.add(f"MA30连续上涨次数：>={ma_up_combo_type15_threshold}")

        interval_lenght = 15
        golden_cross_socre_threshold = 7
        golden_cross_socre = get_golden_cross_socre(
            ma_list_type3, ma_list_type15, length=interval_lenght
        )
        if golden_cross_socre < golden_cross_socre_threshold:
            continue
        condition_list.add(f"{interval_lenght}日内金叉次数：>={golden_cross_socre_threshold}")

        interval_lenght = 15
        throught_up_boll_times_threshold = 1
        throught_up_boll_times = get_throught_up_boll_times(
            candles_data, boll_list_type15, length=15
        )
        if throught_up_boll_times < 1:
            continue
        condition_list.add(
            f"{interval_lenght}日内突破上布林次数：>={throught_up_boll_times_threshold}"
        )

        current_price_threshold_ratio = 0.8
        candles_data_sorted_by_high_price = sorted(
            candles_data, key=lambda x: x[2], reverse=True
        )
        highest_price = candles_data_sorted_by_high_price[0][2]
        if current_price > highest_price * current_price_threshold_ratio:
            continue
        condition_list.add(f"当前价格：<=52周最高价*{current_price_threshold_ratio}")

        name = market_info_all[tx_code][1]
        ths_code = ts_code_to_ths_code(ts_code)
        # price = round(float(market_info_all[tx_code][3]), 1)
        # gains_percent = round(float(market_info_all[tx_code][32]), 1)

        email_info_list.append(
            [
                name,
                ths_code,
                golden_cross_socre,
                ma_up_combo,
                golden_cross_combo,
                current_price,
                gains_percent,
            ]
        )

        email_info_list = sorted(email_info_list, key=lambda x: x[6], reverse=True)

    """
    # https://www.futunn.com/stock/06881-HK/
    https://pqa9p2.smartapps.baidu.com/pages/view/view?code=688317

    名称
    Code
    GxSc
    MaCo
    GxCo
    价格
    涨幅
    """

    # 大盘信息
    up_str_emoji = "🔴"
    down_str_emoji = "🟢"
    up_str = "O"
    down_str = "X"

    ths_code = "hs_1A0001"
    candles_data = ths_.get_candles_data(ths_code)
    ma_list_type3 = get_ma_list(candles_data, ma_type=3, offset=0)
    ma_list_type15 = get_ma_list(candles_data, ma_type=15, offset=0)
    ma_up_combo = get_ma_up_combo(ma_list_type3)
    golden_cross_combo = get_golden_cross_combo(ma_list_type3, ma_list_type15)
    if ma_up_combo > 0:
        emoji1 = up_str_emoji
    else:
        emoji1 = down_str_emoji

    if golden_cross_combo > 0:
        emoji2 = up_str_emoji
    else:
        emoji2 = down_str_emoji

    ths_code2 = "sz_399001"
    candles_data = ths_.get_candles_data(ths_code2)
    ma_list_type3 = get_ma_list(candles_data, ma_type=3, offset=0)
    ma_list_type15 = get_ma_list(candles_data, ma_type=15, offset=0)
    ma_up_combo = get_ma_up_combo(ma_list_type3)
    golden_cross_combo = get_golden_cross_combo(ma_list_type3, ma_list_type15)
    if ma_up_combo > 0:
        emoji3 = up_str_emoji
    else:
        emoji3 = down_str_emoji

    if golden_cross_combo > 0:
        emoji4 = up_str_emoji
    else:
        emoji4 = down_str_emoji

    ths_code3 = "sz_399006"
    candles_data = ths_.get_candles_data(ths_code3)
    ma_list_type3 = get_ma_list(candles_data, ma_type=3, offset=0)
    ma_list_type15 = get_ma_list(candles_data, ma_type=15, offset=0)
    ma_up_combo = get_ma_up_combo(ma_list_type3)
    golden_cross_combo = get_golden_cross_combo(ma_list_type3, ma_list_type15)
    if ma_up_combo > 0:
        emoji5 = up_str_emoji
    else:
        emoji5 = down_str_emoji

    if golden_cross_combo > 0:
        emoji6 = up_str_emoji
    else:
        emoji6 = down_str_emoji

    URL = "https://m.10jqka.com.cn/stockpage/"

    text_content = ""
    text_content += '<div style="text-align:center">'
    text_content += f"<a href='{URL}{ths_code}'>上证</a>"
    text_content += f"：{emoji1}" + "&nbsp;" * 2 + f"{emoji2}"
    text_content += "　" * 1
    text_content += f"<a href='{URL}{ths_code2}'>深成</a>"
    text_content += f"：{emoji3}" + "&nbsp;" * 2 + f"{emoji4}"
    text_content += "　" * 1
    text_content += f"<a href='{URL}{ths_code3}'>创业</a>"
    text_content += f"：{emoji5}" + "&nbsp;" * 2 + f"{emoji6}"
    text_content += "</div>"
    text_content += "<br/>"

    table_head_common = f"""
    <table border="0" align="center"><tr><td align="center" bgcolor="#AFD7F5" width="300">&nbsp;&nbsp;&nbsp;名称&nbsp;&nbsp;&nbsp;</td><td align="center" bgcolor="#AFD7F5" width="80">Code</td><td align="center" bgcolor="#AFD7F5" width="80">GxSc</td><td align="center" bgcolor="#AFD7F5" width="80">MaCo</td><td align="center" bgcolor="#AFD7F5" width="80">GxCo</td><td align="center" bgcolor="#AFD7F5" width="80">价格</td><td align="center" bgcolor="#AFD7F5" width="80">涨幅</td></tr>
    """
    data = email_info_list
    title = ""
    if data.__len__() > 0:
        if len(title) > 0:
            text_content += f"""<div align=center>{title}</div>"""
        text_content += """<div align=center>"""
        text_content += table_head_common
        for item in data:
            name = item[0]
            ths_code = item[1]
            code = ths_code[3:]
            golden_cross_socre = item[2]
            ma_up_combo = item[3]
            golden_cross_combo = item[4]
            price = item[5]
            gains_percent = item[6]
            text_content += f"""<tr><td align="center"><a href='{URL}{ths_code}'>{name}</a></td><td align="center">{code}</td><td align="center">{golden_cross_socre}</td><td align="center">{ma_up_combo}</td><td align="center">{golden_cross_combo}</td><td align="center">{price}</td><td align="center">{gains_percent}</td></tr>"""
        text_content += "</table>"
        text_content += """</div>"""
    else:
        text_content += f"""<div align=center>{title}:无</div>"""
    text_content += "<br/>"

    # 说明信息
    text_content += """</p>"""
    text_content += """<b>筛选条件：</b>""" + "<br/>"
    text_content += """1、流通市值：>=10亿，<=500亿""" + "<br/>"
    text_content += """2、市盈率TTM：>=0，<=20""" + "<br/>"
    text_content += """3、市净率：>=0，<=15""" + "<br/>"
    condition_list = list(condition_list)
    condition_list = sorted(condition_list)
    start_i = 3
    for i in range(len(condition_list)):
        text_content += f"""{start_i + i + 1}、{condition_list[i]}""" + "<br/>"
    text_content += """<p>"""

    # 说明信息
    text_content += """</p>"""
    text_content += """<b>参数说明：</b>""" + "<br/>"
    text_content += """1、K线类型：日K""" + "<br/>"
    text_content += """2、计算金叉均线：MA3，MA15""" + "<br/>"
    text_content += """3、布林线参数：mid=15，std=2""" + "<br/>"
    text_content += """<p>"""

    text_content += "<br/>" * 3

    data = email_info_list
    title = ""
    table_head_common = f"""<table border="0">"""
    if data.__len__() > 0:
        if len(title) > 0:
            text_content += f"""<div align=center>{title}</div>"""
        text_content += """<div align=center>"""
        text_content += table_head_common
        for item in data:
            name = item[0]
            ths_code = item[1]
            code = ths_code[3:]
            text_content += f"""<tr><td align="center"><font size="6">{code}</font></td><td align="center"><font size="6">&nbsp;&nbsp;</font></a></td><td align="center"><a href='{URL}{ths_code}'><font size="6">{name}</font></a></td></tr>"""

            # text_content += f'''<tr><td align="center"><a href='{URL}{ths_code}'><font size="5">{name}</font></a></td><td align="center"><font size="5">&nbsp;&nbsp;{code}</font></td></tr>'''
        text_content += "</table>"
        text_content += """</div>"""
    else:
        text_content += f"""<div align=center>{title}:无</div>"""
    text_content += "<br/>"

    text_content += "<br/>" * 35

    subject = f"股票排行｜{emoji1}{emoji2}｜{emoji3}{emoji4}｜{emoji5}{emoji6}｜{get_timestamp_human()}"
    text = text_content

    send_email_remind(subject, text)


if __name__ == "__main__":
    main()
